package com.xing.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.reggie.common.R;
import com.xing.reggie.dto.SetmealDto;
import com.xing.reggie.entity.Category;
import com.xing.reggie.entity.Dish;
import com.xing.reggie.entity.Setmeal;
import com.xing.reggie.entity.SetmealDish;
import com.xing.reggie.service.CategoryService;
import com.xing.reggie.service.SetmealDishService;
import com.xing.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetMealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐及对应的套餐食品
     * @CacheEvict 新增数据时删除缓存
     * allEntries = true 删除指定名称下所有缓存
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto){
        //调用自定义新增方法
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功！");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件,根据name进行like查询
        queryWrapper.like(name != null,Setmeal::getName,name);
        //添加排序条件，根据更新时间
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //查询
        setmealService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);
            //套餐id
            Long categoryId = item.getCategoryId();
            //通过id得到对应的套餐
            Category category = categoryService.getById(categoryId);
            //得到对应的套餐名称
            if (category != null){
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;

        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);

        return R.success(setmealDtoPage);
    }

    @GetMapping("/{id}")
    @Cacheable(value = "setmealCache",key = "#id")
    @ApiOperation(value = "套餐查询接口")
    @ApiImplicitParam(name = "id",value = "套餐ID",required = true)
    public R<SetmealDto> list(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);

        return R.success(setmealDto);
    }

    /**
     * 根据提交信息进行修改
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "套餐修改接口")
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDish(setmealDto);
        return R.success("修改套餐信息成功！");
    }

    /**
     * 根据id删除对应的套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "套餐删除接口")
    public R<String> delete(@RequestParam List<Long> ids){
        //通过自定义方式删除
        setmealService.deleteWithDish(ids);
        return R.success("删除套餐成功！");
    }

    /**
     * 停售起售操作
     * @CacheEvict 表示删除数据时同时删除缓存
     * allEntries = true 表示删除指定名称下所有缓存
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "套餐状态修改接口")
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids){
        //条件构造器
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        //添加条件
        updateWrapper.set(Setmeal::getStatus,status);
        updateWrapper.in(Setmeal::getId,ids);
        //进行修改
        setmealService.update(updateWrapper);

        return R.success("套餐状态修改成功！");
    }

    /**
     * 根据条件查询套餐下所有信息
     * @param setmeal
     * @Cacheable 查询数据库前先执行查看Redis缓存
     * value 表示某一类缓存，旗下可以有多个key
     * key 缓存key
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    @ApiOperation(value = "套餐查询接口")
    public R<List<Setmeal>> list(Setmeal setmeal){
        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        //只查看状态为1的信息
        queryWrapper.eq(Setmeal::getStatus,1);
        //根据id查询
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        //排序
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //查询
        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);

    }
}
